package excel;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Description: common method
 * Created by E440 on 2017/5/3.
 */
public class UtilExcelCommon {

    /** 获取 workbook
     * @param file
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static Workbook getWorkbook (File file) throws IOException, InvalidFormatException {
        try (InputStream inp= new FileInputStream(file);){
            Workbook wb = WorkbookFactory.create(inp);
            return  wb;
        }
    }

    /** 获取 workbook
     * @param fileAbsPath
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static Workbook getWorkbook (String fileAbsPath) throws IOException, InvalidFormatException {
        try (InputStream inp = new FileInputStream(fileAbsPath)) {
            Workbook wb = WorkbookFactory.create(inp);
            return  wb;
        }

    }

    /** 获取 sheet
     * @param workbook
     * @param index
     * @return
     */
    public static Sheet getSheet(Workbook workbook,int index){
       return workbook.getSheetAt(index);
    }

    /** 获取 sheet
     * @param workbook
     * @param sheetName
     * @return
     */
    public static Sheet getSheet(Workbook workbook,String sheetName){
        return workbook.getSheet(sheetName);
    }

    /** 获取 sheet
     * @param excelFile
     * @param sheetIndex
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
   public static Sheet getSheet(File excelFile ,int sheetIndex) throws IOException, InvalidFormatException {
        return getSheet(getWorkbook(excelFile),sheetIndex);
   }

    /** 获取 sheet
     * @param excelFile
     * @param sheetName
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static Sheet getSheet(File excelFile ,String sheetName) throws IOException, InvalidFormatException {
        return getSheet(getWorkbook(excelFile),sheetName);
    }

    /** 获取 sheet
     * @param fileAbsPath
     * @param sheetName
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static Sheet getSheet(String fileAbsPath ,String sheetName) throws IOException, InvalidFormatException {
        return getSheet(getWorkbook(fileAbsPath),sheetName);
    }
}
